<?php 
	include('config/Config.php');
	header('Content-Type: text/event-stream');
	header('Cache-Control: no-cache');
	$sse = $_GET["sse"];
	if($sse == "true"){
		while(true){
			// get latest event table data
			$dal = new DALSettledContract();
			$data = $dal->getListSettled('modify_timestamp', 'desc', 1, 10);
                        
                        $appInfo = getAppInfo($data);
                        array_unshift($data, $appInfo);
                        
			//echo $data;
			$json = json_encode($data);
			echo "data: {$json}\n\n";
			ob_flush();
			flush();
			sleep(10);
		}
	}else{
		sleep(5);
		$dal = new DALSettledContract();
		$data = $dal->getListSettled('modify_timestamp', 'desc', 1, 10);
		$json = json_encode($data);
		echo "data: {$json}\n\n";
		ob_flush();
		flush();
	}
        
        function getAppInfo($settledContract){
            $dalInfo = new DALUserAccount;
            $balance = $dalInfo->getCurrentBalance();
            $runningCount = 0;
            
            foreach ($settledContract as $ct) {
                if($ct->running === '1'){
                    $runningCount++;
                }
            }
            
            $appInfo = (object) array('balance' => $balance, 'running' => $runningCount);
            
            return $appInfo;
        }
?>